package com.adtech.core.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.adtech.core.dao.query.FilterItem;
import com.adtech.core.dao.query.FilterMap;
import com.adtech.core.dao.query.Pager;
import com.adtech.core.dao.query.Sort;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.Element;

/**
 * Struts2 Action基类

 * @since 2011-6-13
 * @author Dormin
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class BaseAction extends ActionSupport implements SessionAware, RequestAware,ServletRequestAware,ServletResponseAware {

	private static final long serialVersionUID = -1812740908317909399L;

	protected Map<String, Object> session;
	protected Map<String, Object> request;
	protected HttpServletRequest servletRequest;
	protected HttpServletResponse servletResponse;
	private AjaxResult ajaxResult;
	private Pager pager;
	private Sort sorter;
	public String token;
	
	@Element(value = FilterItem.class)
	protected FilterMap filterMap = new FilterMap();
	
	public String getToken() {
		return UUID.randomUUID().toString();
	}

	public AjaxResult getAjaxResult() {
		return ajaxResult;
	}

	public void setAjaxResult(AjaxResult ajaxResult) {
		this.ajaxResult = ajaxResult;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;

	}

	public void setRequest(Map<String, Object> request) {
		this.request = request;

	}

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public Sort getSorter() {
		if (sorter == null) {
			sorter = new Sort();
		}
		return sorter;
	}

	public void setSorter(Sort sorter) {
		this.sorter = sorter;
	}

	public FilterMap getFilterMap() {
		return filterMap;
	}

	public void setFilterMap(FilterMap filterMap) {
		this.filterMap = filterMap;
	}
	
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}
	
	public HttpServletResponse getServletResponse() {
		return servletResponse;
	}
	public void setServletResponse(HttpServletResponse servletResponse) {
		this.servletResponse = servletResponse;
	}
	
	/**
	 * 向页面写入结果
	 * @param result
	 * @author Dormin
	 */
	protected void write(String result) {
		servletResponse.setCharacterEncoding("utf-8");  
		servletResponse.setContentType("text/plain");
		PrintWriter writer=null;
		try {  
			writer = servletResponse.getWriter();
			writer.write(result);
		} catch (IOException e) {}
		writer.flush();  
		writer.close();
	}
}
